﻿using UnityEngine;
using System.Collections;

public class stg3_starter : MonoBehaviour {
    public Camera mainCamera;
    float w = Screen.width;
    float f = 0.0f;
    float h = Screen.height;


    public Texture2D game1_btn;
    public Texture2D game2_btn;
    public Texture2D quit_btn;
    public Texture2D retry_btn;
    bool select_btn1 = false;
    bool select_btn2 = false;
    bool select_quit = false;
    bool select_retry = false;
    bool retry = false;
    bool fail = false;
    bool success = false;
    bool start_stg3 = false;

    AudioClip correct;
    AudioClip wrong;
    GameObject sound_obj;



    public static int currentCard = 0;
    private int preCard = 0;
    private int count = 0;
    private int life_num = 2;
    
    static int[] mixCardNum = new int[17];
    private int[] cardOpen = new int[17];
   
    public enum STATE {INIT, STAGE, TOUCH, IDLE, WAIT}

    public static STATE state = STATE.INIT;
	
	// Update is called once per frame
    void Start()
    {
        correct = (AudioClip)Resources.Load("Sound Files/correct");
        wrong = (AudioClip)Resources.Load("Sound Files/wrong");
        sound_obj = GameObject.FindWithTag("MainCamera");
    }

	void Update () {
        switch (state)
        {
            case STATE.STAGE:
                StartCoroutine("MakeStage");    //특정함수를 멈출 때
                break;     //'(yield return new WaitForSeconds(0.025f)'사용시)
            case STATE.TOUCH:
                StartCoroutine("CheckTouch");
                break;	
        }

        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            mousePos.z = 25.5f;
            Vector3 worldPos = mainCamera.ScreenToWorldPoint(mousePos);
            Instantiate((GameObject)Resources.Load("Prefabs/click1", typeof(GameObject)), worldPos, Quaternion.identity);
        }
        
	}

    void mixCard()
    {
        for (var i = 1; i <= 16; i++)
        {
            mixCardNum[i] = i;		//카드 번호 순서대로 넣기
            cardOpen[i] = 0;		//모든 카드가 뒤집혀진 상태
        }

        for (var i = 1; i <= 10; i++)
        {
            var n1 = Random.Range(1, 16);	//1-16까지 랜덤하게 선택
            var n2 = Random.Range(1, 16);

            var j = mixCardNum[n1];
            mixCardNum[n1] = mixCardNum[n2];
            mixCardNum[n2] = j;
        }	
    }

    IEnumerator MakeStage()     //StartCoroutine사용시 반드시 IEnumerator 사용
    {
        state = STATE.IDLE;		//상태를 wait로 바꾼다
        start_stg3 = true;
        fail = false;
        success = false;
        retry = false;    
	
	    mixCard();
	
	    var x = -6.5f;
	    var y = 5.6f;
	
	    for(var i=1; i<=16; i++){
            var card = Resources.Load("Prefabs/card") as GameObject;    //prefabs로 카드 생성
	        Instantiate(card, new Vector3(x, y, 7), transform.rotation);	//카드 위치 지정			
	    	card.gameObject.tag = "CARD" + mixCardNum[i];	//오브젝트에 tag 설정
		
		    x += 3f;
	    	if(i%4 == 0){		//줄 바꿈
	    		x = -6.5f;
	    		y -= 3f;
	    	}
            yield return new WaitForSeconds(0.025f);    //0.25초 간격으로 카드 배열
    	}
    }

    void OnGUI()
    {
        GUIStyle style = new GUIStyle();
        style.fontSize = 40;
        style.normal.textColor = Color.black;

        if (state == STATE.INIT)
        {
            select_btn1 = GUI.Button(new Rect((2 * w / 5) - (w / 15), 4 * h / 9, h / 4, h / 4), game1_btn);
            select_btn2 = GUI.Button(new Rect((3 * w / 5) - (w / 15), 4 * h / 9, h / 4, h / 4), game2_btn);

            if (select_btn1)
            {
                state = STATE.STAGE;                
            }

            else if (select_btn2)
            {
                DestroyObject(GameObject.FindWithTag("MainCamera"));
                //Application.LoadLevel("aaaaaaaaaaaa");      //게임2넘어가기
            }        
        }

        if (start_stg3)
        {
            string stringToEdit = "Your Life : ";
            string remain_life = life_num + " / 16 ";

            GUI.Label(new Rect(8 * w / 20, 10, 130, 50), stringToEdit, style);
            GUI.DrawTexture(new Rect(10 * w / 20, 10, 8 * w / 20, 40), (Texture)Resources.Load("Images/red"));
            GUI.DrawTexture(new Rect((10 * w / 20) + f, 10, (8 * w / 20) - f, 40), (Texture)Resources.Load("Images/yellow"));
            GUI.Label(new Rect((13 * w / 20) + (w / 40), 10, 130, 50), remain_life, style);
        }

        if (retry)
        {
            select_retry = GUI.Button(new Rect(650, 100, h / 4, h / 4), retry_btn);
            if (select_retry)
            {
                clear();
                state = STATE.STAGE;
                retry = false;
            }
        }

        if (fail)
        {
            start_stg3 = false;
            GUI.Label(new Rect((13 * w / 20) + (w / 40), 10, 130, 50), "You Are Fail !!", style);
        }

        else if (success)
        {
            start_stg3 = false;
            GUI.Label(new Rect((13 * w / 20) + (w / 40), 10, 130, 50), "You Are Success !!", style);
        }

        select_quit = GUI.Button(new Rect(650, 30, h / 4, h / 4), quit_btn);

        if (select_quit)               //나가기버튼 클릭 시
        {
            clear();
            DestroyObject(GameObject.FindWithTag("MainCamera"));
            state = STATE.INIT;         ///////////////////////////////////////////////스테이지3 재로딩가능하게
            Application.LoadLevel("mainMenu");      //Scene전환을 위한 함수
        }
    }

    void clear()
    {
        for (var i = 1; i < 17; i++)
        {
            var obj = GameObject.FindWithTag("CARD" + i);   //tag로 오브젝트 탐색
            Destroy(obj);
        }

        for (var i = 1; i < 17; i++)
        {
            cardOpen[i] = 0;
        }
        currentCard = 0;
        preCard = 0;
        life_num = 16;
        count = 0;
        f = 0.0f;
    }

    IEnumerator CheckTouch()            //11월 15일추가
    {
        state = STATE.IDLE;
        count++;
        yield return new WaitForSeconds(0.5f);
        if (preCard == 0 && count == 1)
        {
            preCard = currentCard;
            count++;
            yield break;
        }
        var selectCard_obj1 = GameObject.FindWithTag("CARD" + currentCard);

        if (preCard == currentCard)
        {
            count = 0;
            selectCard_obj1.renderer.material.mainTexture = (Texture)Resources.Load("Images/stg3/imgBack");
            yield break;
        }

        var card1 = (currentCard + 1) / 2;
        var card2 = (preCard + 1) / 2;

        if (card1 != card2)
        {
            
            sound_obj.audio.PlayOneShot(wrong);
            yield return new WaitForSeconds(0.75f);
            selectCard_obj1.SendMessage("Close", SendMessageOptions.DontRequireReceiver);
            //selectCard_obj1.renderer.material.mainTexture = (Texture)Resources.Load("Images/stg3/imgBack");
            var selectCard_obj2 = GameObject.FindWithTag("CARD" + preCard);
            selectCard_obj2.SendMessage("Close", SendMessageOptions.DontRequireReceiver);
            //selectCard_obj2.renderer.material.mainTexture = (Texture)Resources.Load("Images/stg3/imgBack");
            preCard = 0;
            count = 0;
            life_num -= 1;
            f += (w / 40);
            if (life_num == 0)
            {
                fail = true;
                retry = true;                
            }
            yield break;
        }

        cardOpen[currentCard] = 1;
        cardOpen[preCard] = 1;

        /*var currentCard_obj = GameObject.FindWithTag("CARD" + currentCard);
        currentCard_obj.SendMessage("Open", SendMessageOptions.DontRequireReceiver);

        var preCard_obj = GameObject.FindWithTag("CARD" + preCard);
        preCard_obj.SendMessage("Open", SendMessageOptions.DontRequireReceiver);*/
        sound_obj.audio.PlayOneShot(correct);
        for (int i = 1; i < 17; i++)
        {
            if (cardOpen[i] == 1)
            {
                if (i == 16)
                {
                    success = true;
                    retry = true;
                }
                continue;
            }
            else
            {                
                break;
            }
        }

        preCard = 0;
        count = 0;
    }
    
}
